package com.gyh.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gyh.entity.Member;
import com.gyh.service.MemberService;
import com.gyh.util.JWTUtil;
import com.gyh.util.PasswordUtil;
import com.gyh.util.Result;
import com.gyh.vo.MemberVo;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Resource
    private MemberService memberService;
    @PostMapping
    public Result login(@RequestBody MemberVo member){
        if (ObjectUtil.isEmpty(member.getPhone())){
            return Result.error(401,"账号不能空");
        }
        if (ObjectUtil.isEmpty(member.getCaptcha())) {
            return Result.error(401,"验证码不能为空");
        }
        try {
            Claims claims = JWTUtil.parseJWT(member.getKey());
            String captcha = claims.getSubject();
            if (!captcha.equalsIgnoreCase(member.getCaptcha())){
                return Result.error(401,"验证码不正确");
            }
        } catch (Exception e) {
            return Result.error(401,"验证码已过期");
        }
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        member.setPassword(PasswordUtil.md5encryption(member.getPassword()));
        queryWrapper.eq("phone",member.getPhone()).eq("password",member.getPassword());
        Member one = memberService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(one)){
            return Result.error(401,"账号或密码错误");
        }
        String token = JWTUtil.createJWT(one.getPhone());
        return Result.success(token,one);
    }
    @PostMapping("/register")
    public Result register(@RequestBody MemberVo member){
        if (ObjectUtil.isEmpty(member.getPhone())){
            return Result.error(401,"账号不能空");
        }
        if (ObjectUtil.isEmpty(member.getCaptcha())) {
            return Result.error(401,"验证码不能为空");
        }
        try {
            Claims claims = JWTUtil.parseJWT(member.getKey());
            String captcha = claims.getSubject();
            if (!captcha.equalsIgnoreCase(member.getCaptcha())){
                return Result.error(401,"验证码不正确");
            }
        } catch (Exception e) {
            return Result.error(401,"验证码已过期");
        }
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        member.setPassword(PasswordUtil.md5encryption(member.getPassword()));
        queryWrapper.eq("phone",member.getPhone());
        Member one = memberService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(one)){
            return Result.error(401,"账号已存在，不能重复注册");
        }
        boolean b = memberService.save(member);
        if (!b){
            return Result.error(401,"注册失败");
        }
        String token = JWTUtil.createJWT(member.getPhone());
        return Result.success(token,null);
    }
    @GetMapping("/captcha")
    public Result getCaptcha(){
        // 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.setGenerator(randomGenerator);
        // 重新生成code
        lineCaptcha.createCode();
        String code = JWTUtil.createJWT(lineCaptcha.getCode(),  60 * 1000L);
        String image = lineCaptcha.getImageBase64Data();
        return Result.success(code,image);
    }
    @GetMapping("/getMember")
    public Result getMember(HttpServletRequest request){
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        String token = request.getHeader("token");
        String phone = null;
        try {
            Claims claims = JWTUtil.parseJWT(token);
            phone = claims.getSubject();
        } catch (Exception e) {
            return Result.error(401,"登录失效");
        }
        queryWrapper.eq("phone",phone);
        Member member= memberService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(member)){
            return Result.error(401,"未登录");
        }
        return Result.success(null,member);
    }
}
